package com.hst.capacity.domain.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.brand.BrandUserEntity;
import com.hst.capacity.domain.model.response.auth.LoginUser;
import com.hst.capacity.domain.service.BrandService;
import com.hst.capacity.infra.persistence.jpa.brand.BrandUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private BrandUserRepository userRepository;

    /**
     * 根据userId获取用户实体
     *
     * @param userId 用户ID
     * @return UserEntity
     */
    @Override
    public BrandUserEntity getUser(String userId) {
        return userRepository.findByIdBrandUser(userId);
    }

    @Override
    public LoginUser authenticate(String username, String password) {
        UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(userToken);
        } catch (Exception ex) {
            throw new BusinessException(5002, ex.getMessage());
        }

        if (ObjUtil.isNull(authentication)) {
            throw new BusinessException(5002, "登陆失败！");
        }

        return (LoginUser) authentication.getPrincipal();
    }

}
